package com.maixy.nettyclientdemo;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

/**
 * @ClassName HelloClient
 * @Description TODO
 * @Date 2021/4/7 20:53
 * @Author maixy
 */
@Slf4j
public class HelloSyncClient {
    public static void main(String[] args) throws InterruptedException {
        //启动类
        Bootstrap bootstrap = new Bootstrap()
                //添加EventLoop
                .group(new NioEventLoopGroup())
                //选择客户端Channel实现
                .channel(NioSocketChannel.class)
                //添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override//在建立连接后被调用
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        nioSocketChannel.pipeline().addLast(new StringEncoder());
                    }
                });
        //连接服务器
        ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("localhost", 10003));
        //阻塞方法直到连接建立
        channelFuture = channelFuture.sync();
        Channel channel = channelFuture.channel();
        log.debug("{}", channel);
        //向请求发送数据
        channel.writeAndFlush("Hello World");
    }
}
